import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/views/home/model/leads_follow_info.dart';
import 'package:yuan_hang_app/widget/sort_content.dart';
import 'package:yuan_hang_app/widget/status_btn.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';

import '../res/w_colors.dart';

class WPopupWindow {
  static showSort(
      {Widget? child,
      required BuildContext context,
      double? width,
      SortType sortType = SortType.LEADS_POOL,
      Map? sortParams,
      isScrollControlled = false,
      Function(Map params)? onSelected,
      double radius = 20,
      double padding = 15,
      double? height,
      double buttonWidth = 100,
      double buttonHeight = 40}) {
    showModalBottomSheet(
        context: context,
        isScrollControlled: isScrollControlled,
        // constraints: BoxConstraints(
        //     maxHeight:
        //         height ?? SizeUtils.screenH() - SizeUtils.statusBar() - 44.px,
        //     minHeight: 100.px),
        builder: (_) => Container(
              width: width?.px ?? SizeUtils.screenW(),
              padding: EdgeInsets.all(padding.px),
              constraints: BoxConstraints(
                  maxHeight:
                  height ??   SizeUtils.screenH() - SizeUtils.statusBar() - 44.px,
                  minHeight: 100.px),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(radius.px),
                    topRight: Radius.circular(radius.px)),
                color: Colors.white,
              ),
              child: SortContent(
                sortType: sortType,
                params: sortParams,
                onSelected: (params, isReset) {
                  if (!isReset) {
                    dismiss(context);
                  }
                  sortParams = params;
                  if (onSelected != null) {
                    onSelected(params);
                  }
                },
              ),
            ));
  }

  static dismiss(context) {
    Navigator.pop(context);
  }

  static showSpinner(
      {required List<Map> dataList,
      required BuildContext context,
      String? value,
      double? width,
      Function(String? value, String? label)? onSelected}) {
    showModalBottomSheet(
        context: context,
        builder: (_) => Container(
              height: (dataList.length + 1) * 45.px + 10.px+ SizeUtils.bottomBar(),
              width: width?.px ?? SizeUtils.screenW(),
              color: WColors.CF8F9FA,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Expanded(
                      child: ListView.builder(
                          padding: EdgeInsets.zero,
                          shrinkWrap: true,
                          itemCount: dataList.length,
                          itemBuilder: (context, index) => GestureDetector(
                                onTap: () {
                                  dismiss(context);
                                  if (onSelected != null) {
                                    if (dataList[index]["value"] == value) {
                                      onSelected(null, null);
                                    } else {
                                      onSelected(dataList[index]["value"],
                                          dataList[index]["label"]);
                                    }
                                  }
                                },
                                child: Container(
                                  alignment: Alignment.center,
                                  height: 45.px,
                                  decoration: BoxDecoration(
                                      color: WColors.white,
                                      border: Border(
                                        bottom: BorderSide(
                                          color: WColors.border, // 边框颜色
                                          width: 0.5.px, // 边框宽度
                                        ),
                                      )),
                                  child: WText(
                                    dataList[index]["label"],
                                    style: TextStyle(
                                        fontSize: WDimens.tsMedium,
                                        color: dataList[index]["value"] == value
                                            ? WColors.primaryColor
                                            : WColors.mainTextColor),
                                  ),
                                ),
                              ))),
                  GestureDetector(
                    onTap: () {
                      dismiss(context);
                    },
                    child: Container(
                      margin: EdgeInsets.only(top: 10.px,bottom: SizeUtils.bottomBar()),
                      alignment: Alignment.center,
                      height: 45.px,
                      color: WColors.white,
                      child: WText(
                        "取消",
                        style: TextStyle(
                            fontSize: WDimens.tsMedium,
                            color: WColors.mainTextColor),
                      ),
                    ),
                  )
                ],
              ),
            ));
  }

  static showBooKTime(
      {required List dataList,
      required BuildContext context,
      required Map bookInfo,
      String? selectedTime,
      String? value,
      double? width,
      Function(Map value)? onSelected}) {
    showModalBottomSheet(
        context: context,
        builder: (_) => StatefulBuilder(
                builder: (BuildContext context, StateSetter stateSetter) {
              return Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: WColors.white,
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(30.px),
                        topRight: Radius.circular(30.px))),
                child: Column(
                  children: <Widget>[
                    // 时间段选项网格布局
                    Container(
                      padding: EdgeInsets.all( 15.px),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          GestureDetector(
                            onTap: () {
                              dismiss(context);
                            },
                            child: WText(
                              "取消",
                              style: TextStyle(
                                  color: WColors.hintTextColor,
                                  fontSize: WDimens.tsLarge),
                            ),
                          ),
                          GestureDetector(
                            onTap: () {
                              if (StringUtils.isEmpty(bookInfo["arriveDate"])) {
                                Toast.toast("请先选择预约日期");
                              } else if (StringUtils.isEmpty(
                                  bookInfo["appointTime"])) {
                                Toast.toast("请选择预约时间");
                              } else {
                                ///判断下到店日期是否是当前日期
                                var arriveDate = StringUtils.safeGetValue(
                                    bookInfo["arriveDate"]);
                                String endTimeStr = bookInfo["appointTime"]
                                    .split("-")
                                    .last
                                    .trim();
                                String temp =
                                    "${arriveDate.substring(0, 11)}$endTimeStr:00";
                                // 将字符串转换为DateTime对象
                                DateTime givenDate = DateTime.parse(temp);
                                // 获取当前时间的DateTime对象
                                DateTime now = DateTime.now();
                                // 比较两个日期是否为同一天
                                if (givenDate.year == now.year &&
                                    givenDate.month == now.month &&
                                    givenDate.day == now.day) {
                                  // 比较日期和时间
                                  if (givenDate.isAfter(now)) {
                                    ///允许通过
                                    Navigator.pop(context);
                                    if (onSelected != null) {
                                      onSelected(bookInfo);
                                    }
                                  } else {
                                    Toast.toast("当前时间段预约无效");
                                  }
                                } else {
                                  Navigator.pop(context);
                                  if (onSelected != null) {
                                    onSelected(bookInfo);
                                  }
                                }
                              }
                            },
                            child: WText(
                              "确认",
                              style: TextStyle(
                                color: WColors.primaryColor,
                                fontSize: WDimens.tsLarge,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    WLine(
                      height: 1.px,

                    ),
                    Expanded(
                      child: GridView.builder(
                        padding: EdgeInsets.symmetric(horizontal: 15.px,vertical: 10.px),
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 3,
                          crossAxisSpacing: 10.px,
                          mainAxisSpacing: 10.px,
                          childAspectRatio: 3,
                        ),
                        itemCount: dataList.length,
                        itemBuilder: (context, index) {
                          return StatusBtn(
                              fontSize: WDimens.tsLabel,
                              text: dataList[index]["timeRange"] ?? "请选择",
                              isBg: bookInfo["appointTime"] ==
                                  dataList[index]["timeRange"],
                              color: bookInfo["appointTime"] ==
                          dataList[index]["timeRange"] ?WColors.primaryColor:WColors.hintTextColor,
                              onPressed: () {
                                stateSetter(() {
                                  selectedTime = dataList[index]["timeRange"];
                                  bookInfo["appointTime"] = selectedTime;
                                  bookInfo["resourceId"] =
                                      dataList[index]["id"];
                                  // 这里可以添加其他需要更新状态的代码
                                }); // 关闭弹窗
                              }); // 关闭弹窗
                        },
                      ),
                    ),
                  ],
                ),
              );
            }));
  }

  static showBookTimeForClue(
      {required List dataList,
        required BuildContext context,
        required LeadsFollowInfo leadsFollowInfo,
        String? selectedTime,
        String? value,
        double? width,
        Function(LeadsFollowInfo leadsFollowInfo)? onSelected}) {
    showModalBottomSheet(
        context: context,
        builder: (_) => StatefulBuilder(
            builder: (BuildContext context, StateSetter stateSetter) {
              return Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: WColors.white,
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(30.px),
                        topRight: Radius.circular(30.px))),
                child: Column(
                  children: <Widget>[
                    // 时间段选项网格布局
                    Container(
                      padding: EdgeInsets.all( 15.px),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          GestureDetector(
                            onTap: () {
                              dismiss(context);
                            },
                            child: WText(
                              "取消",
                              style: TextStyle(
                                  color: WColors.hintTextColor,
                                  fontSize: WDimens.tsLarge),
                            ),
                          ),
                          GestureDetector(
                            onTap: () {
                              if (StringUtils.isEmpty(leadsFollowInfo.appointDriveTime)) {
                                Toast.toast("请先选择预约日期");
                              } else if (StringUtils.isEmpty(leadsFollowInfo.appointDriveTimeShow)) {
                                Toast.toast("请选择预约时间");
                              } else {
                                ///判断下到店日期是否是当前日期
                                var arriveDate = leadsFollowInfo.appointDriveTime;
                                String endTimeStr = leadsFollowInfo.appointDriveTimeShow!
                                    .split("-")
                                    .last
                                    .trim();
                                String temp =
                                    "$arriveDate $endTimeStr:00";
                                // 将字符串转换为DateTime对象
                                DateTime givenDate = DateTime.parse(temp);
                                // 获取当前时间的DateTime对象
                                DateTime now = DateTime.now();
                                // 比较两个日期是否为同一天
                                if (givenDate.year == now.year &&
                                    givenDate.month == now.month &&
                                    givenDate.day == now.day) {
                                  // 比较日期和时间
                                  if (givenDate.isAfter(now)) {
                                    ///允许通过
                                    Navigator.pop(context);
                                    if (onSelected != null) {
                                      onSelected(leadsFollowInfo);
                                    }
                                  } else {
                                    Toast.toast("当前时间段预约无效");
                                  }
                                } else {
                                  Navigator.pop(context);
                                  if (onSelected != null) {
                                    onSelected(leadsFollowInfo);
                                  }
                                }
                              }
                            },
                            child: WText(
                              "确认",
                              style: TextStyle(
                                color: WColors.primaryColor,
                                fontSize: WDimens.tsLarge,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    WLine(
                      height: 1.px,

                    ),
                    Expanded(
                      child: GridView.builder(
                        padding: EdgeInsets.symmetric(horizontal: 15.px,vertical: 10.px),
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 3,
                          crossAxisSpacing: 10.px,
                          mainAxisSpacing: 10.px,
                          childAspectRatio: 3,
                        ),
                        itemCount: dataList.length,
                        itemBuilder: (context, index) {
                          return StatusBtn(
                              fontSize: WDimens.tsSmall,
                              text: dataList[index]["timeRange"] ?? "请选择",
                              isBg: leadsFollowInfo.appointDriveTimeShow ==
                                  dataList[index]["timeRange"],
                              color: leadsFollowInfo.appointDriveTimeShow ==
                                  dataList[index]["timeRange"] ?WColors.primaryColor:WColors.hintTextColor,
                              onPressed: () {
                                stateSetter(() {
                                  selectedTime = dataList[index]["timeRange"];
                                  leadsFollowInfo.appointDriveTimeShow = selectedTime;
                                  leadsFollowInfo.appointDriveResourceId = int.parse(dataList[index]["id"]);
                                  // 这里可以添加其他需要更新状态的代码
                                }); // 关闭弹窗
                              }); // 关闭弹窗
                        },
                      ),
                    ),
                  ],
                ),
              );
            }));
  }
  
}
